package com.learn.grpc.loadbalance;

import io.grpc.LoadBalancer;
import io.grpc.LoadBalancerProvider;
import io.grpc.NameResolver;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class LbLoadBalancerProvider extends LoadBalancerProvider {

    @Override
    public boolean isAvailable() {
        return true;
    }

    @Override
    public int getPriority() {
        // 优先级
        return 10;
    }

    @Override
    public NameResolver.ConfigOrError parseLoadBalancingPolicyConfig(Map<String, ?> rawLoadBalancingPolicyConfig) {
        // 自定义配置项，可以传给自定义 CustomLoadBalancer
        return NameResolver.ConfigOrError.fromConfig(rawLoadBalancingPolicyConfig);
    }

    @Override
    public String getPolicyName() {
        // 负载策略名称，注册后，客户端通过该名称选择路由策略
        return "custom_round_robin";
    }

    @Override
    public LoadBalancer newLoadBalancer(LoadBalancer.Helper helper) {
        // 每一个服务会创建一个 loadBalancer
        LbLoadBalancer lbLoadBalancer = new LbLoadBalancer(helper);
        log.info("创建 lbLoadBalancer:{}", lbLoadBalancer);
        return lbLoadBalancer;
    }
}
